package com.example.demo.JsonTest;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author LHH
 * @date 2025/4/15
 */
public class JsonATest {

    public static void main(String[] args) {
        String inputFilePath = "C:\\Users\\admin\\Desktop\\Work\\沿海\\物资库对接\\json\\YHJK_FINANCIAL_MONTH.json";
        splitJsonFile(inputFilePath, 20);
    }


    public static void splitJsonFile(String inputFilePath, int numParts) {
        try {
            // 读取 JSON 文件内容
            String jsonContent = readFile(inputFilePath);
            // 解析 JSON 数组
            JsonArray jsonArray = JsonParser.parseString(jsonContent).getAsJsonArray();
            // 分割 JSON 数组
            List<JsonArray> parts = splitJsonArray(jsonArray, numParts);
            // 保存分割后的内容到新文件
            savePartsToFiles(parts, inputFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String readFile(String filePath) throws IOException {
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
        }
        return content.toString();
    }

    private static List<JsonArray> splitJsonArray(JsonArray jsonArray, int numParts) {
        List<JsonArray> parts = new ArrayList<>();
        int totalSize = jsonArray.size();
        int partSize = (int) Math.ceil((double) totalSize / numParts);
        for (int i = 0; i < totalSize; i += partSize) {
            JsonArray part = new JsonArray();
            for (int j = i; j < Math.min(i + partSize, totalSize); j++) {
                JsonElement element = jsonArray.get(j);
                part.add(element);
            }
            parts.add(part);
        }
        return parts;
    }

    private static void savePartsToFiles(List<JsonArray> parts, String inputFilePath) throws IOException {
        Gson gson = new Gson();
        for (int i = 0; i < parts.size(); i++) {
            String outputFilePath = getOutputFilePath(inputFilePath, i + 1);
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath))) {
                writer.write(gson.toJson(parts.get(i)));
            }
        }
    }

    private static String getOutputFilePath(String inputFilePath, int partNumber) {
        java.io.File inputFile = new java.io.File(inputFilePath);
        String fileName = inputFile.getName();
        String baseName = fileName.substring(0, fileName.lastIndexOf('.'));
        String extension = fileName.substring(fileName.lastIndexOf('.'));
        return baseName + "_part" + partNumber + extension;
    }
}
